const state = {
  user: {
    token: null,
    username: null,
    photo: null,
    userId: null
  },
  headerCss: false
};

const getters = {
  isLogin: state => {
    if (state.user.token == null) {
      state.user.token = localStorage.getItem('token');
    }
    return state.user.token != null;
  },
  token: state => {
    if (state.user.token == null) {
      state.user.token = localStorage.getItem('token');
    }
    return state.user.token;
  },
  username: state => {
    if (state.user.username == null) {
      state.user.username = localStorage.getItem('username');
    }
    return state.user.username;
  },
  userId: state => {
    if (state.user.userId == null) {
      state.user.userId = localStorage.getItem('userId');
    }
    return state.user.userId;
  },
  photo: state => {
    if (state.user.photo == null) {
      state.user.photo = localStorage.getItem('photo');
    }
    return state.user.photo;
  },
  headerCss: state => {
    return state.headerCss;
  }
};
const mutations = {
  login(state, {user}) {
    state.user.token = user.token;
    localStorage.setItem('token', user.token);
  },
  logout(state) {
    state.user.token = null;
    state.user.username = null;
    state.user.photo = null;
    state.user.userId = null;
    localStorage.removeItem('userId');
    localStorage.removeItem('token');
    localStorage.removeItem('username');
    localStorage.removeItem('photo');
  },
  updateUserInfo(state, {user}) {

    state.user.username = user.username;
    state.user.photo = user.photo;
    state.user.userId = user.userId;

    localStorage.setItem('username', user.username);
    localStorage.setItem('photo', user.photo);
    localStorage.setItem('userId', user.userId);
  },
  changeStatus(state, {status}) {
    state.headerCss = status;
  }
};

const actions = {
  login({state, commit}, user) {
    commit('login', {user});
  },
  logout({commit}) {
    commit('logout');
  },
  updateUserInfo({state, commit}, user) {
    commit('updateUserInfo', {user});
  },
  updateHeadStatu({state, commit}, status) {
    commit('changeStatus', {status});
  }
};

export default {
  state,
  getters,
  mutations,
  actions
};
